const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 创建通知
 */
exports.createNotification = async (req, res) => {
  try {
    const {
      title,
      content,
      type = 'text',
      imageUrl = null,
      priority = 'normal',
      targetType,
      targetIds = null,
      expiresAt = null
    } = req.body;

    const senderId = req.user?.id || null;
    const senderName = req.user?.username || 'System';

    // 验证必填字段
    if (!title || !content || !targetType) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 验证targetType
    if (!['all', 'user', 'client'].includes(targetType)) {
      return res.status(400).json({
        success: false,
        message: '无效的目标类型'
      });
    }

    // 验证targetIds
    if (targetType !== 'all' && !targetIds) {
      return res.status(400).json({
        success: false,
        message: '请指定目标ID'
      });
    }

    // 转换targetIds为JSON字符串
    const targetIdsJson = targetIds ? JSON.stringify(targetIds) : null;

    // 插入通知
    const [result] = await db.query(
      `INSERT INTO notifications 
       (title, content, type, image_url, priority, target_type, target_ids, sender_id, sender_name, expires_at) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [title, content, type, imageUrl, priority, targetType, targetIdsJson, senderId, senderName, expiresAt]
    );

    const notificationId = result.insertId;

    const notification = {
      id: notificationId,
      title,
      content,
      type,
      imageUrl,
      priority,
      targetType,
      targetIds,
      senderId,
      senderName,
      createdAt: new Date(),
      expiresAt
    };

    // 通过WebSocket实时推送通知
    const socketManager = req.app.get('socketManager');
    if (socketManager) {
      socketManager.sendNotificationToTargets(notification);
    }

    logger.info(`✉️  创建通知: ${title} -> ${targetType} (ID: ${notificationId})`);

    res.json({
      success: true,
      message: '通知创建成功',
      data: notification
    });
  } catch (error) {
    logger.error('创建通知失败:', error);
    res.status(500).json({
      success: false,
      message: '创建通知失败: ' + error.message
    });
  }
};

/**
 * 获取客户端/用户的通知列表
 */
exports.getNotifications = async (req, res) => {
  try {
    const { page = 1, pageSize = 20, isRead, clientId } = req.query;
    const userId = req.user?.id;
    const offset = (page - 1) * pageSize;

    // 验证用户身份
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }

    // 构建查询条件
    let whereConditions = ['n.is_active = 1'];
    let params = [];

    // 目标过滤：all（全部）、特定用户、特定客户端
    if (clientId) {
      whereConditions.push(`(
        n.target_type = 'all' 
        OR (n.target_type = 'client' AND JSON_CONTAINS(n.target_ids, ?))
        OR (n.target_type = 'user' AND JSON_CONTAINS(n.target_ids, ?))
      )`);
      params.push(JSON.stringify(clientId), JSON.stringify(userId.toString()));
    } else {
      whereConditions.push(`(
        n.target_type = 'all' 
        OR (n.target_type = 'user' AND JSON_CONTAINS(n.target_ids, ?))
      )`);
      params.push(JSON.stringify(userId.toString()));
    }

    const whereClause = whereConditions.join(' AND ');

    // 获取总数
    const [countResult] = await db.query(
      `SELECT COUNT(DISTINCT n.id) as total 
       FROM notifications n
       WHERE ${whereClause}`,
      params
    );
    const total = countResult[0]?.total || 0;

    // 查询通知列表，并关联已读状态
    const query = `
      SELECT 
        n.*,
        nr.is_read,
        nr.read_at,
        UNIX_TIMESTAMP(n.created_at) * 1000 as created_at_ts
      FROM notifications n
      LEFT JOIN notification_reads nr ON (
        n.id = nr.notification_id 
        AND (nr.user_id = ? OR nr.client_id = ?)
      )
      WHERE ${whereClause}
      ${isRead !== undefined ? 'AND (nr.is_read = ? OR nr.is_read IS NULL)' : ''}
      ORDER BY n.created_at DESC
      LIMIT ? OFFSET ?
    `;

    const queryParams = [userId || null, clientId || null, ...params];
    if (isRead !== undefined) {
      queryParams.push(parseInt(isRead));
    }
    queryParams.push(parseInt(pageSize), offset);

    const [notifications] = await db.query(query, queryParams);

    // 解析target_ids JSON字符串
    const formattedNotifications = notifications.map(n => ({
      ...n,
      target_ids: n.target_ids ? JSON.parse(n.target_ids) : null,
      is_read: n.is_read === null ? false : !!n.is_read
    }));

    res.json({
      success: true,
      data: {
        notifications: formattedNotifications,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    logger.error('获取通知列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取通知列表失败: ' + error.message
    });
  }
};

/**
 * 标记通知为已读
 */
exports.markAsRead = async (req, res) => {
  try {
    const { id } = req.params;
    const { isRead = true, clientId } = req.body;
    const userId = req.user?.id;

    // 检查通知是否存在
    const [notifications] = await db.query(
      'SELECT * FROM notifications WHERE id = ? AND is_active = 1',
      [id]
    );

    if (notifications.length === 0) {
      return res.status(404).json({
        success: false,
        message: '通知不存在'
      });
    }

    // 插入或更新已读记录
    await db.query(
      `INSERT INTO notification_reads (notification_id, user_id, client_id, is_read, read_at)
       VALUES (?, ?, ?, ?, NOW())
       ON DUPLICATE KEY UPDATE is_read = ?, read_at = NOW()`,
      [id, userId, clientId, isRead ? 1 : 0, isRead ? 1 : 0]
    );

    logger.info(`📖 通知已${isRead ? '读' : '标记为稍后再读'}: ${id} (用户: ${userId}, 客户端: ${clientId})`);

    res.json({
      success: true,
      message: isRead ? '已标记为已读' : '已标记为稍后再读'
    });
  } catch (error) {
    logger.error('标记通知状态失败:', error);
    res.status(500).json({
      success: false,
      message: '标记通知状态失败: ' + error.message
    });
  }
};

/**
 * 获取未读通知数量
 */
exports.getUnreadCount = async (req, res) => {
  try {
    const { clientId } = req.query;
    const userId = req.user?.id;

    const query = `
      SELECT COUNT(DISTINCT n.id) as count
      FROM notifications n
      LEFT JOIN notification_reads nr ON (
        n.id = nr.notification_id 
        AND (nr.user_id = ? OR nr.client_id = ?)
      )
      WHERE n.is_active = 1
        AND (
          n.target_type = 'all' 
          OR (n.target_type = 'client' AND JSON_CONTAINS(n.target_ids, ?))
          OR (n.target_type = 'user' AND JSON_CONTAINS(n.target_ids, ?))
        )
        AND (nr.is_read IS NULL OR nr.is_read = 0)
    `;

    const [result] = await db.query(query, [
      userId, 
      clientId, 
      JSON.stringify(clientId), 
      JSON.stringify(userId.toString())
    ]);

    res.json({
      success: true,
      data: {
        count: result[0].count
      }
    });
  } catch (error) {
    logger.error('获取未读数量失败:', error);
    res.status(500).json({
      success: false,
      message: '获取未读数量失败: ' + error.message
    });
  }
};

/**
 * 管理员获取所有通知（含已读状态统计）
 */
exports.getAllNotifications = async (req, res) => {
  try {
    const { page = 1, pageSize = 20, targetType } = req.query;
    const offset = (page - 1) * pageSize;

    let whereClause = 'WHERE 1=1';
    let params = [];

    if (targetType) {
      whereClause += ' AND n.target_type = ?';
      params.push(targetType);
    }

    // 获取总数
    const [countResult] = await db.query(
      `SELECT COUNT(*) as total FROM notifications n ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // 查询通知列表，统计已读/未读数量
    const query = `
      SELECT 
        n.*,
        UNIX_TIMESTAMP(n.created_at) * 1000 as created_at_ts,
        COUNT(DISTINCT CASE WHEN nr.is_read = 1 THEN nr.id END) as read_count,
        COUNT(DISTINCT CASE WHEN nr.is_read = 0 THEN nr.id END) as unread_count,
        COUNT(DISTINCT nr.id) as total_recipients
      FROM notifications n
      LEFT JOIN notification_reads nr ON n.id = nr.notification_id
      ${whereClause}
      GROUP BY n.id
      ORDER BY n.created_at DESC
      LIMIT ? OFFSET ?
    `;

    const [notifications] = await db.query(query, [...params, parseInt(pageSize), offset]);

    // 解析target_ids
    const formattedNotifications = notifications.map(n => ({
      ...n,
      target_ids: n.target_ids ? JSON.parse(n.target_ids) : null
    }));

    res.json({
      success: true,
      data: {
        notifications: formattedNotifications,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    logger.error('获取通知管理列表失败:', error);
    
    // 检查是否是表不存在的错误
    if (error.code === 'ER_NO_SUCH_TABLE') {
      return res.status(500).json({
        success: false,
        message: '通知表不存在，请先创建数据库表'
      });
    }
    
    res.status(500).json({
      success: false,
      message: '获取通知管理列表失败: ' + error.message
    });
  }
};

/**
 * 获取单个通知的详细已读状态
 */
exports.getNotificationReadStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, pageSize = 50 } = req.query;
    const offset = (page - 1) * pageSize;

    // 获取通知信息
    const [notifications] = await db.query(
      'SELECT * FROM notifications WHERE id = ?',
      [id]
    );

    if (notifications.length === 0) {
      return res.status(404).json({
        success: false,
        message: '通知不存在'
      });
    }

    const notification = notifications[0];

    // 获取已读记录
    const query = `
      SELECT 
        nr.*,
        u.username,
        u.nickname,
        c.hostname,
        UNIX_TIMESTAMP(nr.read_at) * 1000 as read_at_ts
      FROM notification_reads nr
      LEFT JOIN users u ON nr.user_id = u.id
      LEFT JOIN clients c ON nr.client_id = c.client_id
      WHERE nr.notification_id = ?
      ORDER BY nr.read_at DESC
      LIMIT ? OFFSET ?
    `;

    const [reads] = await db.query(query, [id, parseInt(pageSize), offset]);

    // 获取总数
    const [countResult] = await db.query(
      'SELECT COUNT(*) as total FROM notification_reads WHERE notification_id = ?',
      [id]
    );
    const total = countResult[0].total;

    res.json({
      success: true,
      data: {
        notification: {
          ...notification,
          target_ids: notification.target_ids ? JSON.parse(notification.target_ids) : null
        },
        reads,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    logger.error('获取通知已读状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取通知已读状态失败: ' + error.message
    });
  }
};

/**
 * 删除通知（软删除）
 */
exports.deleteNotification = async (req, res) => {
  try {
    const { id } = req.params;

    // 软删除：设置 is_active = 0
    await db.query(
      'UPDATE notifications SET is_active = 0 WHERE id = ?',
      [id]
    );

    logger.info(`🗑️  通知已删除: ${id}`);

    res.json({
      success: true,
      message: '通知已删除'
    });
  } catch (error) {
    logger.error('删除通知失败:', error);
    res.status(500).json({
      success: false,
      message: '删除通知失败: ' + error.message
    });
  }
};

